package xusage.cumulus.spring.resolver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.web.context.support.ServletContextResourcePatternResolver;

public class CumulusResourcePatternResolver extends ServletContextResourcePatternResolver {

	public CumulusResourcePatternResolver() {
		super(new DefaultResourceLoader());
	}
	
	public CumulusResourcePatternResolver(ClassLoader classLoader) {
		super(new DefaultResourceLoader(classLoader));
	}
	
	public CumulusResourcePatternResolver(ResourceLoader resourceLoader) {
		super(resourceLoader);
	}
	
	public CumulusResourcePatternResolver(ServletContext servletContext) {
		super(servletContext);		
	}
	
	public Resource[] getResources(String locationPattern) throws IOException {
		Assert.notNull(locationPattern, "Location pattern must not be null");	
		if (locationPattern.indexOf(CUMULUS_URL_PREFIX) > -1) {
			String replacedLocationPattern = locationPattern.substring(locationPattern.indexOf(CUMULUS_URL_PREFIX) + CUMULUS_URL_PREFIX.length());
			List<Resource> resources = new ArrayList<Resource>();
			for (String prefix : REPLACED_URL_PREFIXES) {
				String currentLocationPattern = (prefix + replacedLocationPattern).replace('\\', '/');				
				LOGGER.trace("Loading : {} -> {}", locationPattern, currentLocationPattern);				
				try {
					for(Resource resource : super.getResources(currentLocationPattern)) {
						resources.add(resource);
						LOGGER.trace("Found resource : {}", resource.getURL());
					}					
				}
				catch (IOException ex) {
					LOGGER.warn("Trying to load replaced location failded : {}, {}", currentLocationPattern, ex.getMessage());
				}				
			}			
			return resources.toArray(new Resource[resources.size()]);
		}
		else {
			return super.getResources(locationPattern);
		}
	}

	private static final String[] REPLACED_URL_PREFIXES = new String[] {
		"WEB-INF/lib/*.jar!",
		CLASSPATH_ALL_URL_PREFIX
	};
	
	private static final String CUMULUS_URL_PREFIX = "cumulus:";
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CumulusResourcePatternResolver.class);
}
